//
//  BDOrderViewController.m
//  BadBoy
//
//  Created by wen on 2017/7/6.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDOrderViewController.h"
#import "BDUserModel.h"
#import "BDReservationModel.h"
#import "BDReservationTableViewCell.h"
#import "BDDetailReservationViewController.h"
#import "BDCouponValidationView.h"
#import "BDShopEditCommondViewController.h"
#import "BDOrderModel.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "AppDelegate.h"

@interface BDOrderViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger currentSelectedIndex;
}

@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *topView;
@end

@implementation BDOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"我的订单");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if (self.datasource.count && currentSelectedIndex != 1) {
        [self.tableView reloadData];
    }else{
        [self.datasource removeAllObjects];
        self.startPage = @"1";
        [self requestDatasourceNeedHud:YES];
    }
}

- (void)requestDatasourceNeedHud:(BOOL)needHud{
    if (needHud == YES) {
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
    }
    
    //未付款，这里需要单独另外一个接口和处理
    if (currentSelectedIndex == 1) {
        NSString *url = [NSString stringWithFormat:@"%@payment/orders?page=%@&size=%@&status=0&type=4", KBDBaseURL, self.startPage, self.pageSize];
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            [self.datasource addObjectsFromArray:[BDOrderModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
            self.startPage = x[@"next_page"];
            self.isEnd = [x[@"is_end"] boolValue];
            [self.tableView reloadData];
            
            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                [self.datasource removeAllObjects];
                self.startPage = @"1";
                [self requestDatasourceNeedHud:NO];
            }];
            self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [self requestDatasourceNeedHud:NO];
            }];
            
            [self setReservationTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager hideAlert];
            if (self.datasource.count == 0) {
                [self showErrorViewWithTapBlock:^{
                    
                }];
            }
        }];
    }else{
        NSArray *array = nil;
        if (currentSelectedIndex == 0) {
            //全部
            array = nil;
        }else if (currentSelectedIndex == 2) {
            //未使用
            array = @[[NSString stringWithFormat:@"%@", @(BDReservationStatusNotUse)]];
        }else if (currentSelectedIndex == 3) {
            //已失效
            array = @[[NSString stringWithFormat:@"%@", @(BDReservationStatusOverdue)],
                      [NSString stringWithFormat:@"%@", @(BDReservationStatusRefunded)]];
        }
        
        NSDictionary *para = nil;
        if (array == nil) {
            para = @{@"page":self.startPage,
                     @"size":self.pageSize};
        }else{
            NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            para = @{@"page":self.startPage,
                     @"size":self.pageSize,
                     @"status":jsonStr};
        }
        
        NSString *url = [NSString stringWithFormat:@"%@shopCouponPurchases", KBDBaseURL];
        
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            [self.datasource addObjectsFromArray:[BDReservationModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
            self.startPage = x[@"next_page"];
            self.isEnd = [x[@"is_end"] boolValue];
            [self.tableView reloadData];
            
            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                [self.datasource removeAllObjects];
                self.startPage = @"1";
                [self requestDatasourceNeedHud:NO];
            }];
            self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [self requestDatasourceNeedHud:NO];
            }];
            
            [self setReservationTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager hideAlert];
            if (self.datasource.count == 0) {
                [self showErrorViewWithTapBlock:^{
                    
                }];
            }
        }];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 159;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDReservationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reservationCell" forIndexPath:indexPath];
    id model = self.datasource[indexPath.section];
    [cell configeWithModel:model buttonClickBlock:^{
        if ([model isKindOfClass:[BDReservationModel class]]) {
            BDReservationModel *reservation = model;
            if (reservation.status == BDReservationStatusNotUse) {
                //使用
//                BDCouponValidationView *couponValidationView = [BDCouponValidationView couponValidationViewWithReservation:reservation];
//                [couponValidationView show];
            }else if (reservation.status == BDReservationStatusUsed) {
                //评价
                BDShopEditCommondViewController *shopEditCommondVC = [[BDShopEditCommondViewController alloc] init];
//                if (shopEditCommondVC.reservationModel.shop == nil) {
//                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该商家已被删除")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
//                    return;
//                }
                shopEditCommondVC.couponsModel = nil;
                [self.navigationController pushViewController:shopEditCommondVC animated:YES];
            }
        }else if ([model isKindOfClass:[BDOrderModel class]]) {
            AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            appDelegate.payResultBlock = ^(int state) {
                if (state == 1) {
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                        //这里刷新页面
                        UIButton *button = [self.topView viewWithTag:1417];
                        [button sendActionsForControlEvents:UIControlEventTouchUpInside];
                    }];
                }else if (state == 2) {
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付发生错误")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
                }else if (state == 3) {
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付取消")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
                }
            };
            BDOrderModel *order = model;
            if (order.channel == 0) {
                [self aliPayWithPara:order];
            }else if (order.channel == 1) {
                [self wxPayWithPara:order];
            }
        }
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BDDetailReservationViewController *detailReservationVC = [[BDDetailReservationViewController alloc] init];
    BDReservationModel *reservation = self.datasource[indexPath.section];
    if (reservation.shop == nil) {
        [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该商家已被删除")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        return;
    }
    detailReservationVC.model = reservation;
    [self.navigationController pushViewController:detailReservationVC animated:YES];
}

- (void)aliPayWithPara:(BDOrderModel *)order{
    NSString *appScheme = @"beBoyAliPay";
    [[AlipaySDK defaultService] payOrder:order.payment_info fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSInteger stateCode = [resultDic[@"resultStatus"] integerValue];
        if (stateCode == 9000) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                //这里刷新页面
                UIButton *button = [self.topView viewWithTag:1417];
                [button sendActionsForControlEvents:UIControlEventTouchUpInside];
            }];
        }else if (stateCode == 4000) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付发生错误")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        }else if (stateCode == 6001) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付取消")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        }
    }];
}

- (void)wxPayWithPara:(BDOrderModel *)order{
    
    NSData *jsonData = [order.payment_info dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *x = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    PayReq *request = [[PayReq alloc] init];
    request.openID = x[@"app_id"];
    request.partnerId = x[@"merchant_id"];
    request.prepayId = x[@"prepay_id"];
    request.package = @"Sign=WXPay";
    request.nonceStr= x[@"nonce_str"];
    request.timeStamp= (UInt32)[x[@"timestamp"] integerValue];
    request.sign= x[@"sign"];
    [WXApi sendReq:request];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.bottom, kBDScreenWidth, kBDScreenHeight - self.topView.bottom) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        [_tableView registerClass:[BDReservationTableViewCell class] forCellReuseIdentifier:@"reservationCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorInset = UIEdgeInsetsZero;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)topView{
    if (!_topView) {
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, 45)];
        [self.view addSubview:_topView];
        
        UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 45)];
        head.backgroundColor = kBDColorGray;
        head.bottom = _topView.height;
        [_topView addSubview:head];
        
        UIView *contenView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 40)];
        contenView.backgroundColor = [UIColor whiteColor];
        [head addSubview:contenView];
        
        NSArray *buttArr = @[ASLocalizedString(@"全部"),ASLocalizedString(@"待付款"),ASLocalizedString(@"待使用"), ASLocalizedString(@"已失效")];
        CGFloat buttonWidth = 70;
        CGFloat space = (kBDScreenWidth - buttonWidth * buttArr.count) / (buttArr.count + 1);
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(space, 0, buttonWidth, 1.5)];
        lineView.backgroundColor = KBDColorBlue;
        lineView.bottom = contenView.height;
        [contenView addSubview:lineView];
        
        for (int i = 0; i < buttArr.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(space + (space + buttonWidth)*i, 0, buttonWidth, 40);
            [button setTitle:buttArr[i] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"#1c1c1c"] forState:UIControlStateNormal];
            [button setTitleColor:KBDColorBlue forState:UIControlStateSelected];
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            button.tag = 1415 + i;
            [contenView addSubview:button];
            if (i == 0) {
                button.selected = YES;
                currentSelectedIndex = i;
            }
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if ( i == currentSelectedIndex) {
                    // BDLog(ASLocalizedString(@"点击了相同的按钮"));
                    return;
                }
                UIButton *oldButton = [contenView viewWithTag:1415 + currentSelectedIndex];
                oldButton.selected  = NO;
                
                [UIView animateWithDuration:0.3 animations:^{
                    lineView.centerX = button.centerX;
                } completion:^(BOOL finished) {
                    button.selected = YES;
                    currentSelectedIndex = i;
                    
                    [self.datasource removeAllObjects];
                    self.startPage = @"1";
                    [self requestDatasourceNeedHud:YES];
                }];
            }];
        }
    }
    return _topView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
